package com.base.vistter.iframe.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.base.vistter.iframe.bean.SystemContextHolder;
import com.base.vistter.iframe.entity.SysDepart;
import com.base.vistter.iframe.entity.SysJob;
import com.base.vistter.iframe.entity.SysRole;
import com.base.vistter.iframe.entity.SysUser;
import com.base.vistter.iframe.exception.IframeException;
import com.base.vistter.iframe.mapper.SysUserMapper;
import com.base.vistter.iframe.utils.ToolUtils;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
@Slf4j
public class SysUserService extends BaseService<SysUserMapper, SysUser> {

    @Resource(name = "sysDepartService")
    private SysDepartService sysDepartService;
    @Resource(name = "sysRoleService")
    private SysRoleService sysRoleService;
    @Resource(name = "sysJobService")
    private SysJobService sysJobService;

    @Resource(name = "passwordEncoder")
    private PasswordEncoder passwordEncoder;

    @Transactional(readOnly = true)
    public Page<SysUser> findPager(Page<SysUser> page, String username, String workNo, String phone, Integer sysDepartId) throws IframeException {
        LambdaQueryWrapper<SysUser> lambdaQueryWrapper = new LambdaQueryWrapper<SysUser>();
        if (sysDepartId != null) {
            List<Integer> departIds = sysDepartService.getRootChildrenIds(sysDepartId);
            lambdaQueryWrapper.in(SysUser::getSysDepartId, departIds);
        }
        if (StringUtils.isNotEmpty(username)) {
            lambdaQueryWrapper.like(SysUser::getUsername, username);
        }
        if (StringUtils.isNotEmpty(workNo)) {
            lambdaQueryWrapper.like(SysUser::getWorkNo, workNo);
        }
        if (StringUtils.isNotEmpty(phone)) {
            lambdaQueryWrapper.like(SysUser::getPhone, phone);
        }
        if (!ToolUtils.isAdmin()) {
            if (ToolUtils.isBusAdmin()) {
                lambdaQueryWrapper.ne(SysUser::getIsAdmin, 1);
            } else {
                lambdaQueryWrapper.eq(SysUser::getIsAdmin, 0);
            }
        }
        return super.page(page, lambdaQueryWrapper);
    }

    @Transactional(propagation = Propagation.REQUIRED)
    public boolean save(SysUser entity) throws IframeException {
        entity.setIsAdmin(0);
        LambdaQueryWrapper<SysUser> lambdaQueryWrapper = new LambdaQueryWrapper<SysUser>();
        lambdaQueryWrapper.eq(SysUser::getUsername, entity.getUsername());
        boolean isExit = super.exists(lambdaQueryWrapper);
        if (isExit) {
            throw new IframeException("用户名已经存在");
        }
        entity.setPassword(passwordEncoder.encode(entity.getPassword()));
        return super.save(entity);
    }

    @Transactional(propagation = Propagation.REQUIRED)
    public boolean update(SysUser entity) throws IframeException {
        entity.setPassword(passwordEncoder.encode(entity.getPassword()));
        return super.updateById(entity);
    }

    @Transactional(propagation = Propagation.REQUIRED)
    public boolean updateStatus(Integer id, Integer status) throws IframeException {
        SysUser sysUser = this.baseMapper.selectById(id);
        sysUser.setStatus(status);
        return super.updateById(sysUser);
    }

    @Transactional(propagation = Propagation.REQUIRED)
    public SysUser getSysUserByUsername(String username) throws IframeException {
        return this.baseMapper.getSysUserByUsername(username);
    }

    @Transactional(propagation = Propagation.REQUIRED)
    public boolean pass(Integer id, String password) throws IframeException {
        SysUser sysUser = this.getBaseMapper().selectById(id);
        sysUser.setPassword(passwordEncoder.encode(password));
        return super.retBool(this.getBaseMapper().updateById(sysUser));
    }

    @Transactional(propagation = Propagation.REQUIRED)
    public boolean repass(String password) throws IframeException {
        SysUser sysUser = this.getBaseMapper().selectById(SystemContextHolder.getSessionContext().getUserId());
        sysUser.setPassword(passwordEncoder.encode(password));
        return super.retBool(this.getBaseMapper().updateById(sysUser));
    }

    @Transactional(readOnly = true)
    public Page<SysUser> getPageUser(Page<SysUser> page, String username, String phone) throws IframeException {
        LambdaQueryWrapper<SysUser> lambdaQueryWrapper = new LambdaQueryWrapper<SysUser>();
        if (StringUtils.isNotEmpty(username)) {
            lambdaQueryWrapper.like(SysUser::getUsername, username);
        }
        if (StringUtils.isNotEmpty(phone)) {
            lambdaQueryWrapper.like(SysUser::getPhone, phone);
        }
        lambdaQueryWrapper.like(SysUser::getStatus, 0);
        if (!ToolUtils.isAdmin()) {
            if (ToolUtils.isBusAdmin()) {
                lambdaQueryWrapper.ne(SysUser::getIsAdmin, 1);
            } else {
                lambdaQueryWrapper.eq(SysUser::getIsAdmin, 0);
            }
        }
        return super.page(page, lambdaQueryWrapper);
    }

    @Transactional(readOnly = true)
    public SysUser getCurrentUser() throws IframeException {
        SysUser sysUser = super.getById(SystemContextHolder.getSessionContext().getUserId());
        if (sysUser.getSysDepartId() != null) {
            SysDepart sysDepart = sysDepartService.getById(sysUser.getSysDepartId());
            sysUser.setSysDepartName(sysDepart.getName());
        }
        if (sysUser.getSysRoleId() != null) {
            SysRole sysRole = sysRoleService.getById(sysUser.getSysRoleId());
            sysUser.setSysRoleName(sysRole.getName());
        }
        if (sysUser.getSysJobId() != null) {
            SysJob sysJob = sysJobService.getById(sysUser.getSysJobId());
            sysUser.setSysJobName(sysJob.getName());
        }
        return sysUser;
    }

    @Transactional(propagation = Propagation.REQUIRED)
    public boolean updateCurrentUser(SysUser sysUser) throws IframeException {
        SysUser user = getCurrentUser();
        sysUser.setId(user.getId());
        return super.updateById(sysUser);
    }
}
